import { todosList } from './valtio/state';
import {useSnapshot} from 'valtio';
import {useRef} from 'react';
function AddTodo(){
    const textRef = useRef();
    const handleSubmit = (event)=>{
        event.preventDefault();
        todosList.todos.push({
            id:todosList.todos.length+1,
            text:textRef.current.value,
            completed:false
        });
    }
    return (
        <form onSubmit={handleSubmit}>
            <input ref={textRef}/>
            <input type="submit"/>
        </form>
    )
}
function TodoList() {
    //useSnapshot会返回一个只读的，不可变的快照对象
    //这个快照对象会在状态发生变化时自动更新
    const snapshot = useSnapshot(todosList);
    return (
        <ul>
            {
                snapshot.todos.map(todo => (
                    <li key={todo.id}>
                        <input
                            type="checkbox"
                            checked={todo.completed}
                            onChange={() => {
                                let oldTodo = todosList.todos.find(item => item.id === todo.id);
                                if (oldTodo) {
                                    oldTodo.completed = !oldTodo.completed;
                                }
                            }} />
                        {todo.text}
                    </li>
                ))
            }
        </ul>
    )
}
function ValtioApp() {
    return (
        <>
            <AddTodo/>
            <TodoList/>
        </>
    )
}
export default ValtioApp;